from .models import Book, BookPush, BookPushLog
from celery import task
import celery
from task_config.models import ScheduleCronConf, ScheduleCronConfLog
import datetime
import time

class BaseTaskCrontab(celery.Task):
    def on_success(self, retval, task_id, args, kwargs):
        # print(task_id)
        use_time = retval['use_time']
        status = retval['status']
        cron_id = args[0]
        # print(retval, cron_id)
        cron_conf = ScheduleCronConf.objects.get(id=cron_id)
        cron_log = ScheduleCronConfLog(status=status, user_time=use_time, cron=cron_conf)
        cron_log.save()

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        print(exc)
        print(args)
        print(kwargs)

        # use_time = kwargs['use_time']
        # status = kwargs['status']
        # cron_id = args[0]
        # cron_conf = ScheduleCronConf.objects.get(id=cron_id)
        # cron_log = ScheduleCronConfLog(status=status, user_time=use_time, cron=cron_conf)
        # cron_log.save()


# 注意：如果使用bind=True，任务第一个参数一定要传self（这个任务对象）
@task(bind=True, base=BaseTaskCrontab)
def push_book(self, cron_id):
    try:
        start_time = datetime.datetime.now()
        book = Book.objects.order_by('-count').first()
        BookPush.objects.all().delete()
        book_push = BookPush(book=book)
        book_push.save()
        book_push_log = BookPushLog(book=book)
        book_push_log.save()
        end_time = datetime.datetime.now()
        use_time = end_time - start_time

        return {'status': 'success', 'use_time': use_time}
    except Exception as e:
        return {'status': 'fail', 'use_time': str(e)}
